package com.ujiuye.Servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginCookieServlet")
public class LoginCookieServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        boolean res=true;
        if (res){
            //成功
            //判断用户是否需要记住密码
            //如果一组复选框中只有一个复选框，可以直接使用getParameter就可以
            String rem=req.getParameter("rem");
            if ("ok".equals(rem)){
                Cookie nameCookie=new Cookie("username",username);
                nameCookie.setMaxAge(60*60*24*15);
                resp.addCookie(nameCookie);
                Cookie pwdCookie=new Cookie("password",password);
                pwdCookie.setMaxAge(60*60*24*15);
                resp.addCookie(pwdCookie);
            }else {
                //取消之前记住的密码
                //利用Cookie覆盖特性，将之前同名的Cookie覆盖删除掉
                Cookie nameCookie=new Cookie("username",null);
                nameCookie.setMaxAge(0);
                resp.addCookie(nameCookie);
                Cookie pwdCookie=new Cookie("password",null);
                pwdCookie.setMaxAge(0);
                resp.addCookie(pwdCookie);
            }
            resp.sendRedirect("index.jsp");
        }else {
            resp.sendRedirect("login_cookie.jsp");
        }
    }
}
